package org.zjvis.datascience.web.api;

import cn.weiguangfu.swagger2.plus.annotation.ApiPlus;
import com.google.common.base.Joiner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.zjvis.datascience.common.dto.user.UserDTO;
import org.zjvis.datascience.common.model.ApiResult;
import org.zjvis.datascience.common.model.ApiResultCode;
import org.zjvis.datascience.common.util.JwtUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description 用户cookie接口 Controller
 * @date 2021-09-23
 */
@ApiPlus(value = true)
@RestController
@RequestMapping("/testcookie")
@Api(tags = "cookieApi", description = "用户cookie接口")
@Validated
public class TestCookie{

  public static final String COOKIE_PLUGIN = "plugin";

  @PostMapping(value = "/saveCookie")
  @ResponseBody
  @ApiOperation(value = "新增cookie", notes = "新增cookie")
  public ApiResult<Void> saveCookie(HttpServletRequest req, HttpServletResponse resp){
      resp.addCookie(gen(JwtUtil.getCurrentUserDTO()));
      return ApiResult.valueOf(ApiResultCode.SUCCESS);
  }



  @PostMapping(value = "/queryCookie")
  @Transactional
  @ResponseBody
  @ApiOperation(value = "获取cookie", notes = "获取cookie")
  public ApiResult<String> queryCookie(HttpServletRequest req, HttpServletResponse resp){
    Cookie cookies[] = req.getCookies();
    Cookie graphAnalysisCookie = null;
    for (Cookie cookie : cookies) {
      if (cookie.getName().equals(COOKIE_PLUGIN)) {
        graphAnalysisCookie = cookie;
      }
    }
    if (graphAnalysisCookie != null) {
      return ApiResult.valueOf(graphAnalysisCookie.getValue());
    } else {
      return ApiResult.valueOf(ApiResultCode.SYS_ERROR);
    }
  }

  private Cookie gen(UserDTO user) {
    Cookie cookie = new Cookie(COOKIE_PLUGIN, Joiner.on("_").join(user.getId(), user.getStatus(), user.getRole()));
    cookie.setMaxAge(60 * 60 * 24 * 7);
    cookie.setPath("/"); //具体路径
    return cookie;
  }

}
